import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  Typography
} from 'antd'
import {
  SearchOutlined,
  ReloadOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker
const { Option } = Select
const { Title } = Typography

// 日志级别枚举
enum LogLevel {
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error',
  DEBUG = 'debug'
}

// 日志数据接口
interface LogData {
  id: string
  timestamp: string
  level: LogLevel
  message: string
  source: string
  userId?: string
  ip?: string
  userAgent?: string
  details?: string
}

// 日志统计数据接口
interface LogStats {
  total: number
  info: number
  warn: number
  error: number
  debug: number
}

const Logs: React.FC = () => {
  // 状态管理
  const [logs, setLogs] = useState<LogData[]>([])
  const [loading, setLoading] = useState(false)
  const [searchText, setSearchText] = useState('')
  const [selectedLevel, setSelectedLevel] = useState<string>('all')
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null] | null>(null)
  const [stats, setStats] = useState<LogStats>({
    total: 0,
    info: 0,
    warn: 0,
    error: 0,
    debug: 0
  })

  // 生成假数据
  const generateMockLogs = (): LogData[] => {
    const levels = [LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.DEBUG]
    const sources = ['用户管理', '系统设置', '权限管理', '数据库', '缓存', 'API网关']
    const messages = [
      '用户登录成功',
      '用户登录失败，密码错误',
      '数据库连接超时',
      '缓存更新完成',
      'API调用频率过高',
      '系统配置更新',
      '权限验证失败',
      '文件上传成功',
      '内存使用率过高',
      '定时任务执行完成'
    ]

    const mockLogs: LogData[] = []
    
    for (let i = 0; i < 100; i++) {
      const level = levels[Math.floor(Math.random() * levels.length)]
      const source = sources[Math.floor(Math.random() * sources.length)]
      const message = messages[Math.floor(Math.random() * messages.length)]
      
      mockLogs.push({
        id: `log_${i + 1}`,
        timestamp: dayjs().subtract(Math.floor(Math.random() * 7), 'day')
          .subtract(Math.floor(Math.random() * 24), 'hour')
          .subtract(Math.floor(Math.random() * 60), 'minute')
          .format('YYYY-MM-DD HH:mm:ss'),
        level,
        message,
        source,
        userId: Math.random() > 0.5 ? `user_${Math.floor(Math.random() * 1000)}` : undefined,
        ip: `192.168.1.${Math.floor(Math.random() * 255)}`,
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        details: level === LogLevel.ERROR ? '详细错误信息...' : undefined
      })
    }

    return mockLogs.sort((a, b) => dayjs(b.timestamp).valueOf() - dayjs(a.timestamp).valueOf())
  }

  // 计算统计数据
  const calculateStats = (logData: LogData[]): LogStats => {
    const stats = {
      total: logData.length,
      info: 0,
      warn: 0,
      error: 0,
      debug: 0
    }

    logData.forEach(log => {
      stats[log.level]++
    })

    return stats
  }

  // 获取日志级别对应的颜色和图标
  const getLevelConfig = (level: LogLevel) => {
    switch (level) {
      case LogLevel.INFO:
        return { color: 'blue', icon: <InfoCircleOutlined /> }
      case LogLevel.WARN:
        return { color: 'orange', icon: <ExclamationCircleOutlined /> }
      case LogLevel.ERROR:
        return { color: 'red', icon: <CloseCircleOutlined /> }
      case LogLevel.DEBUG:
        return { color: 'green', icon: <CheckCircleOutlined /> }
      default:
        return { color: 'default', icon: <InfoCircleOutlined /> }
    }
  }

  // 表格列配置
  const columns: ColumnsType<LogData> = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
      sorter: (a, b) => dayjs(a.timestamp).valueOf() - dayjs(b.timestamp).valueOf(),
      defaultSortOrder: 'descend'
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: (level: LogLevel) => {
        const config = getLevelConfig(level)
        return (
          <Tag color={config.color} icon={config.icon}>
            {level.toUpperCase()}
          </Tag>
        )
      },
      filters: [
        { text: 'INFO', value: LogLevel.INFO },
        { text: 'WARN', value: LogLevel.WARN },
        { text: 'ERROR', value: LogLevel.ERROR },
        { text: 'DEBUG', value: LogLevel.DEBUG }
      ],
      onFilter: (value, record) => record.level === value
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      width: 120,
      filters: [
        { text: '用户管理', value: '用户管理' },
        { text: '系统设置', value: '系统设置' },
        { text: '权限管理', value: '权限管理' },
        { text: '数据库', value: '数据库' },
        { text: '缓存', value: '缓存' },
        { text: 'API网关', value: 'API网关' }
      ],
      onFilter: (value, record) => record.source === value
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: {
        showTitle: false
      },
      render: (message: string) => (
        <Tooltip placement="topLeft" title={message}>
          {message}
        </Tooltip>
      )
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 120,
      render: (userId?: string) => userId || '-'
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
      width: 140
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              onClick={() => handleViewDetails(record)}
            >
              详情
            </Button>
          </Tooltip>
        </Space>
      )
    }
  ]

  // 初始化数据
  useEffect(() => {
    loadLogs()
  }, [])

  // 加载日志数据
  const loadLogs = () => {
    setLoading(true)
    // 模拟API调用延迟
    setTimeout(() => {
      const mockLogs = generateMockLogs()
      setLogs(mockLogs)
      setStats(calculateStats(mockLogs))
      setLoading(false)
    }, 1000)
  }

  // 搜索处理
  const handleSearch = () => {
    // 这里可以实现实际的搜索逻辑
    console.log('搜索条件:', { searchText, selectedLevel, dateRange })
    loadLogs()
  }

  // 重置搜索条件
  const handleReset = () => {
    setSearchText('')
    setSelectedLevel('all')
    setDateRange(null)
    loadLogs()
  }

  // 导出日志
  const handleExport = () => {
    // 这里可以实现导出功能
    console.log('导出日志')
  }

  // 查看详情
  const handleViewDetails = (record: LogData) => {
    // 这里可以实现查看详情的逻辑
    console.log('查看详情:', record)
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>系统日志监控</Title>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总日志数"
              value={stats.total}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="信息日志"
              value={stats.info}
              valueStyle={{ color: '#52c41a' }}
              prefix={<InfoCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="警告日志"
              value={stats.warn}
              valueStyle={{ color: '#faad14' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="错误日志"
              value={stats.error}
              valueStyle={{ color: '#f5222d' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和过滤区域 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Input
              placeholder="搜索日志消息"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col span={4}>
            <Select
              style={{ width: '100%' }}
              placeholder="选择日志级别"
              value={selectedLevel}
              onChange={setSelectedLevel}
            >
              <Option value="all">全部级别</Option>
              <Option value={LogLevel.INFO}>INFO</Option>
              <Option value={LogLevel.WARN}>WARN</Option>
              <Option value={LogLevel.ERROR}>ERROR</Option>
              <Option value={LogLevel.DEBUG}>DEBUG</Option>
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              style={{ width: '100%' }}
              value={dateRange}
              onChange={setDateRange}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Col>
          <Col span={8}>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
              <Button icon={<ReloadOutlined />} onClick={loadLogs}>
                刷新
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 日志表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            total: logs.length,
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  )
}

export default Logs